﻿package com.agileai.miscdp.hotweb.ui.editors.standard;

import java.io.File;
import java.io.StringWriter;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;

import com.agileai.miscdp.hotweb.domain.BaseFuncModel;
import com.agileai.miscdp.hotweb.domain.ListTabColumn;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.PageParameter;
import com.agileai.miscdp.hotweb.domain.standard.StandardFuncModel;
import com.agileai.miscdp.hotweb.ui.editors.BaseModelEditor;
import com.agileai.miscdp.hotweb.ui.views.TreeObject;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.hotweb.model.EditTableType;
import com.agileai.hotweb.model.ListTableType;
import com.agileai.hotweb.model.QueryBarType;
import com.agileai.hotweb.model.standard.StandardFuncModelDocument;
import com.agileai.util.FileUtil;
import com.agileai.util.StringUtil;
/**
 * 单表操作功能模型编辑器
 */
public class StandardModelEditor extends BaseModelEditor{
	private SMBasicConfigPage sMBasicConfigPage;
	private SMListJspCfgPage sMListJspCfgPage;
	private SMDetailJspCfgPage sMDetailJspCfgPage;
	
    public void init(IEditorSite site, IEditorInput input) throws PartInitException {
        setSite(site);
        setInput(input);
        setPartName(input.getName());
		init();
		ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
    }
	private void init() {
		funcModel = (StandardFuncModel)this.getEditorInput();
	}

	protected void createPages() {
		sMBasicConfigPage = new SMBasicConfigPage(getContainer(),this,SWT.NONE);
		sMListJspCfgPage = new SMListJspCfgPage(getContainer(),this,SWT.NONE);
		sMDetailJspCfgPage = new SMDetailJspCfgPage(getContainer(),this,SWT.NONE);
		
		String basicConfig = MiscdpUtil.getIniReader().getValue("EditorInfo","BasicInfo");
		int basicConfigIndex = addPage(sMBasicConfigPage);
		setPageText(basicConfigIndex,basicConfig);
		sMBasicConfigPage.createContent();
		
		String listJspConfig = MiscdpUtil.getIniReader().getValue("EditorInfo","ListInfo");
		int listJspCfgIndex = addPage(sMListJspCfgPage);
		setPageText(listJspCfgIndex,listJspConfig);
		sMListJspCfgPage.createContent();
		
		String detailJspConfig = MiscdpUtil.getIniReader().getValue("EditorInfo","DetailInfo");
		int detailJspCfgIndex = addPage(sMDetailJspCfgPage);
		setPageText(detailJspCfgIndex, detailJspConfig);
		sMDetailJspCfgPage.createContent();
		
		initValues();
		
		sMBasicConfigPage.registryModifier();
		sMListJspCfgPage.registryModifier();
		sMDetailJspCfgPage.registryModifier();
	}
	public void doSave(IProgressMonitor monitor) {
		try {
			StandardFuncModel suFuncModel = buildFuncModel();
	    	String projectName = suFuncModel.getProjectName();
	    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
	    	
	    	String abstSqlMapPath = project.getLocation().toString()+"/src/sqlmap";
	    	File tempFile = new File(abstSqlMapPath);
	    	if (!tempFile.exists()){
	    		tempFile.mkdirs();
	    	}
	    	String sql = sMBasicConfigPage.getListSqlText().getText();
	    	if (StringUtil.isNullOrEmpty(sql)){
	    		String sqlCheckNullMsg = MiscdpUtil.getIniReader().getValue("StandardModelEditor","SqlCheckNullMsg");
	    		DialogUtil.showInfoMessage(sqlCheckNullMsg);
	    		return;
	    	}
	    	
	    	StandardFuncModelDocument funcModelDocument = (StandardFuncModelDocument)buildFuncModelDocument(suFuncModel);
			StringWriter writer = new StringWriter();
			funcModelDocument.save(writer);
			String funcName = suFuncModel.getFuncName();
			String funcSubPkg = suFuncModel.getFuncSubPkg();
			
			String funcDefine = writer.toString();
			String funcId = suFuncModel.getFuncId();
			String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
			FileUtil.writeFile(fileName, funcDefine);

//			String tableName = suFuncModel.getTableName();
//	    	String sqlMapFileName = MiscdpUtil.getValidName(tableName); 
//	    	String sqlMapFile = abstSqlMapPath + "/" + sqlMapFileName+".xml";
//	    	SMSqlMapGenerator sqlGenerator = new SMSqlMapGenerator(projectName); 
//			String[] colNames = MiscdpUtil.getColNames(suFuncModel.getPageFormFields());
//			String findRecordsSql = suFuncModel.getListSql();
//			sqlGenerator.setColNames(colNames);
//			sqlGenerator.setFindRecordsSql(findRecordsSql);
//	    	sqlGenerator.setTableName(tableName);
//	    	sqlGenerator.setSqlMapFile(sqlMapFile);
//	    	sqlGenerator.generate();
			
			this.isModified = false;
			firePropertyChange(PROP_DIRTY);
			
			TreeViewer funcTreeViewer = funcModelTree.getFuncTreeViewer();
			ISelection selection = funcTreeViewer.getSelection();
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			TreeObject treeObject = null;
			if (obj instanceof TreeObject) {
				treeObject = (TreeObject) obj;
				treeObject.setName(funcName);
				treeObject.setFuncSubPkg(funcSubPkg);
			}

			updateIndexFile(projectName);
			
			this.setPartName(funcName);
			funcTreeViewer.refresh();
			try {
				suFuncModel.buildFuncModel(funcDefine);
				project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SMBasicConfigPage getBasicConfigPage() {
		return sMBasicConfigPage;
	}
	public SMListJspCfgPage getListJspCfgPage() {
		return sMListJspCfgPage;
	}
	public SMDetailJspCfgPage getDetailJspCfgPage() {
		return sMDetailJspCfgPage;
	}

	public StandardFuncModel buildFuncModel() {
		this.sMBasicConfigPage.buildConfig();
		this.sMListJspCfgPage.buildConfig();
		return this.sMDetailJspCfgPage.buildConfig();
	}
	public void initValues() {
		this.sMBasicConfigPage.initValues();
		this.sMListJspCfgPage.initValues();
		this.sMDetailJspCfgPage.initValues();
	}
	public StandardFuncModel getFuncModel() {
		return (StandardFuncModel)funcModel;
	}
	public Object buildFuncModelDocument(BaseFuncModel baseFuncModel){
		StandardFuncModel standardFuncModel = (StandardFuncModel)baseFuncModel;
		StandardFuncModelDocument funcModelDocument = StandardFuncModelDocument.Factory.newInstance();
		StandardFuncModelDocument.StandardFuncModel funcModel = funcModelDocument.addNewStandardFuncModel();
		StandardFuncModelDocument.StandardFuncModel.BaseInfo baseInfo = funcModel.addNewBaseInfo();
		String tableName = standardFuncModel.getTableName();
		String detailJspName = standardFuncModel.getDetailJspName();
		String listJspName = standardFuncModel.getListJspName();
		baseInfo.setDetailJspName(detailJspName);
		baseInfo.setDetailTitle(standardFuncModel.getDetailTitle());
		baseInfo.setTemplate(standardFuncModel.getTemplate());
		baseInfo.setListJspName(listJspName);
		baseInfo.setListTitle(standardFuncModel.getListTitle());
		baseInfo.setQueryListSql(standardFuncModel.getListSql());
		baseInfo.setTableName(tableName);
		baseInfo.setPkGenPolicy(standardFuncModel.getPkGenPolicy());
		
		StandardFuncModelDocument.StandardFuncModel.BaseInfo.Service service = baseInfo.addNewService();
		String interfaceName = standardFuncModel.getInterfaceName();
		service.setServiceId(standardFuncModel.getServiceId());
		service.setImplClassName(standardFuncModel.getImplClassName());
		service.setInterfaceName(interfaceName);
		
		String editHandlerId = detailJspName.substring(0,detailJspName.length()-4);
		editHandlerId = editHandlerId.substring(editHandlerId.lastIndexOf("/")+1,editHandlerId.length());
		String listHandlerId = listJspName.substring(0,listJspName.length()-4);
		listHandlerId = listHandlerId.substring(listHandlerId.lastIndexOf("/")+1,listHandlerId.length());
		String tempClassPath = interfaceName.substring(0,interfaceName.lastIndexOf(".")).replace("bizmoduler","controller"); 
		String listHandlerClass = tempClassPath + "." + listHandlerId + "Handler";
		String editHandlerClass = tempClassPath + "." + editHandlerId + "Handler";
		StandardFuncModelDocument.StandardFuncModel.BaseInfo.Handler handler = baseInfo.addNewHandler();
		handler.setEditHandlerId(editHandlerId);
		handler.setEditHandlerClass(editHandlerClass);
		handler.setListHandlerId(listHandlerId);
		handler.setListHandlerClass(listHandlerClass);
		
		StandardFuncModelDocument.StandardFuncModel.BaseInfo.SqlResource sqlResource = baseInfo.addNewSqlResource();
		
		sqlResource.setSqlNameSpace(tableName.toLowerCase());
		String sqlMapPath = "sqlmap/"+tableName+".xml";;
		sqlResource.setSqlMapPath(sqlMapPath);
		
		StandardFuncModelDocument.StandardFuncModel.ListView listView = funcModel.addNewListView();
		List<PageParameter> pageParameters = standardFuncModel.getPageParameters();
		
		QueryBarType queryBarType = listView.addNewParameterArea(); 
		this.processQueryBarType(queryBarType, pageParameters);
		
		ListTableType listTableType = listView.addNewListTableArea();
		listTableType.setExportCsv(standardFuncModel.isExportCsv());
		listTableType.setExportXls(standardFuncModel.isExportXls());
		listTableType.setPagination(standardFuncModel.isPagination());
		listTableType.setSortAble(standardFuncModel.isSortAble());
		
		List<ListTabColumn> listTabColumns = standardFuncModel.getListTableColumns();
		String rsIdColumn = StringUtils.join(standardFuncModel.getRsIdColumns().toArray(),",");
		
		this.processListTableType(listTableType, listTabColumns, rsIdColumn);
		
		StandardFuncModelDocument.StandardFuncModel.DetailView detailView = funcModel.addNewDetailView();
		EditTableType editTableType = detailView.addNewDetailEditArea();
		List<PageFormField> pageFormFields = standardFuncModel.getPageFormFields();
		this.processEditTableType(editTableType, pageFormFields);

		return funcModelDocument;
	}
}
